from flask import Blueprint, request, jsonify, render_template
from app.models.db import get_db
import time
from datetime import datetime
from flask_login import login_required
zero_stock_bp = Blueprint('zero_stock', __name__)

# 同步记录页面
@zero_stock_bp.route('/sync/logs')
def sync_logs_page():
    return render_template('sync_logs.html')

# 零库存订单页面
@zero_stock_bp.route('/zero-stock/orders')
def zero_stock_orders_page():
    return render_template('zero_stock_orders.html')

# 创建零库存订单（带/api前缀）
@zero_stock_bp.route('/api/order/zero-stock', methods=['POST'])
@login_required
def create_zero_stock_order():
    data = request.get_json()
    required = ['supplier_id', 'product_id', 'quantity']
    if not all(k in data for k in required):
        return jsonify({'status': 'error', 'message': '缺少参数（供应商ID、商品ID、数量）'}), 400
    try:
        quantity = int(data['quantity'])
        if quantity <= 0:
            return jsonify({'status': 'error', 'message': '数量必须为正数'}), 400
    except ValueError:
        return jsonify({'status': 'error', 'message': '数量必须是数字'}), 400

    db = get_db()
    cursor = db.cursor()

    try:
        cursor.execute("""
        SELECT si.*, s.supplier_name FROM supplier_inventory si
        JOIN supplier s ON si.supplier_id = s.id
        WHERE si.supplier_id=? AND si.product_id=?
        """, (data['supplier_id'], data['product_id']))
        item = cursor.fetchone()
        if not item:
            return jsonify({'status': 'error', 'message': '该供应商无此商品虚拟库存'}), 404
        if item['virtual_quantity'] < quantity:
            return jsonify({'status': 'error', 'message': f'虚拟库存不足（当前：{item["virtual_quantity"]}）'}), 400

        # 扣减虚拟库存
        new_qty = item['virtual_quantity'] - quantity
        update_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute("""
        UPDATE supplier_inventory SET virtual_quantity=?, update_time=? WHERE id=?
        """, (new_qty, update_time, item['id']))

        # 生成订单并写入表
        order_id = f"ZERO-{int(time.time())}"
        cursor.execute('''
        INSERT INTO zero_stock_order (
            order_id, supplier_id, supplier_name, product_id, product_name,
            quantity, create_time, operator
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ''', (
            order_id,
            data['supplier_id'], item['supplier_name'],
            data['product_id'], item['product_name'],
            quantity, update_time,
            "admin"
        ))

        db.commit()
        return jsonify({
            'status': 'success',
            'message': '零库存订单创建成功',
            'order_id': order_id,
            'remaining_virtual_quantity': new_qty
        })
    except Exception as e:
        db.rollback()
        return jsonify({'status': 'error', 'message': f'订单创建失败：{str(e)}'}), 500

# 查询虚拟库存同步记录（带/api前缀）
@zero_stock_bp.route('/api/supplier/sync/logs', methods=['GET'])
@login_required
def get_sync_logs():
    supplier_id = request.args.get('supplier_id', '')
    product_id = request.args.get('product_id', '')
    cursor = get_db().cursor()
    query = "SELECT * FROM supplier_inventory_sync_log WHERE 1=1"
    params = []
    if supplier_id:
        query += " AND supplier_id=?"
        params.append(supplier_id)
    if product_id:
        query += " AND product_id=?"
        params.append(product_id)
    query += " ORDER BY sync_time DESC"
    cursor.execute(query, params)
    return jsonify([dict(row) for row in cursor.fetchall()])

# 查询零库存订单记录（带/api前缀）
@zero_stock_bp.route('/api/order/zero-stock/list', methods=['GET'])
@login_required
def get_zero_stock_orders():
    supplier_id = request.args.get('supplier_id', '')
    status = request.args.get('status', '')
    cursor = get_db().cursor()
    query = "SELECT * FROM zero_stock_order WHERE 1=1"
    params = []
    if supplier_id:
        query += " AND supplier_id=?"
        params.append(supplier_id)
    if status:
        query += " AND status=?"
        params.append(status)
    query += " ORDER BY create_time DESC"
    cursor.execute(query, params)
    return jsonify([dict(row) for row in cursor.fetchall()])

# 更新零库存订单状态（带/api前缀）
@zero_stock_bp.route('/api/order/zero-stock/status', methods=['POST'])
@login_required
def update_order_status():
    data = request.get_json()
    required = ['order_id', 'status']
    if not all(k in data for k in required):
        return jsonify({'status': 'error', 'message': '缺少参数（订单号、状态）'}), 400
    valid_status = ['已创建', '已发货', '已完成', '已取消']
    if data['status'] not in valid_status:
        return jsonify({'status': 'error', 'message': f'状态必须是：{",".join(valid_status)}'}), 400

    cursor = get_db().cursor()
    cursor.execute("UPDATE zero_stock_order SET status=? WHERE order_id=?", (data['status'], data['order_id']))
    get_db().commit()
    return jsonify({'status': 'success', 'message': '订单状态更新成功'})